<template>
  <div class="add-container">
    <div class="add-top">
      <el-page-header @back="goBack" :content="gobacktitle"></el-page-header>
    </div>
    <div class="add-main">
      <div class="add-main-top">
        <div class="add-main-tital">
          <p>维修单</p>
        </div>
        <div>
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            :rules="rules"
            label-position="left"
            label-width="0.8rem"
            class="demo-ruleForm"
          >
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="名称" prop="mingcheng">
                  <el-input
                    v-model="ruleForm.mingcheng"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="状态">
                  <el-select
                    v-model="ruleForm.zhuangtai"
                    :disabled="true"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in $util.getwxdzt()"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注">
                  <el-input
                    v-model="ruleForm.tips"
                    placeholder="请输入备注"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="submit-button" v-if="gobacktitle == '新增'">
            <el-button
              type="primary"
              icon="el-icon-circle-check"
              @click="submitForm('ruleForm')"
            >
              确认
            </el-button>
            <el-button type="info" icon="el-icon-delete" @click="goBack">
              取消
            </el-button>
          </div>
        </div>
      </div>
      <div class="add-main-list" v-if="gobacktitle == '编辑'">
        <div class="list-button-group">
          <div class="button-item">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="DialogOpenWuzi()"
            >
              新增任务单
            </el-button>
          </div>
        </div>
        <div class="table-list" id="table-list">
          <ux-grid
            border
            show-overflow
            ref="plxTable"
            keep-source
            :height="tabheight"
            :highlightCurrentRow="false"
            widthResize
            @selection-change="selectChange"
            :edit-config="{ trigger: 'click', mode: 'row' }"
          >
            <ux-table-column type="checkbox" width="50" />
            <ux-table-column
              type="index"
              title="序号"
              width="50"
            ></ux-table-column>
            <ux-table-column field="renwudh" title="任务单号"></ux-table-column>
            <ux-table-column field="guajia" title="挂架"></ux-table-column>
            <ux-table-column field="zhuangtai" title="状态">
              <template v-slot="scope">
                {{ $util.getBfrwdzt(scope.row.zhuangtai) }}
              </template>
            </ux-table-column>
            <!-- <ux-table-column
              field="createName"
              title="创建人"
            ></ux-table-column>
            <ux-table-column
              field="createTime"
              title="创建日期"
            ></ux-table-column> -->
            <ux-table-column title="操作" width="100">
              <template v-slot="{ row }">
                <!-- <el-button type="text" @click="handleDelete(row)">
                  删除
                </el-button> -->
                <el-dropdown @command="handleDelete(row)" trigger="click">
                  <span
                    class="el-dropdown-link"
                    style="padding: 0 10px; color: #2171d4"
                  >
                    更多
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="1">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </ux-table-column>
          </ux-grid>
          <div class="submit-button">
            <el-button
              type="primary"
              icon="el-icon-circle-check"
              @click="submitForm('ruleForm')"
            >
              确认
            </el-button>
            <el-button type="info" icon="el-icon-delete" @click="goBack">
              取消
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <!--新增 物资 -->
    <page-1-add-wuzi
      ref="wuzi-dialog"
      @fetch-data="fetchData"
      :dataBH="ruleForm"
      :alltable="alltable"
    ></page-1-add-wuzi>
  </div>
</template>
<script>
  import {
    queryWXOne,
    addWxd,
    updateWxd,
    queryWXRWDListAll,
    deleteWXRWD,
    addWXRWD,
    updateguajia,
  } from '@/api/kunei'
  import page1AddWuzi from './page1AddWuzi.vue'
  export default {
    name: 'Page1Add',
    components: { page1AddWuzi },
    props: {
      gobacktitle: {
        type: String,
        default: '新增',
        required: true,
      },
      datarow: {
        type: Object,
        default: function () {
          return {}
        },
      },
    },
    data() {
      return {
        show: true,
        insertData: {},
        ruleForm: {
          zhuangtai: 1,
        },
        rules: {
          mingcheng: [
            { required: true, message: '请输入名称', trigger: 'blur' },
          ],
        },
        tabheight: 500,
        importShow: false,
        alltable: [],
        Rwlist: [],
      }
    },
    created() {},
    async mounted() {
      if (this.gobacktitle == '编辑') {
        let { data } = await queryWXOne({ id: this.datarow.id })
        this.ruleForm = Object.assign({}, data)
        this.ruleForm.zhuangtai = data.zhuangtai ? data.zhuangtai : 1
        this.getRwList()
      }
      let height = document.getElementById('table-list').offsetHeight
      this.tabheight = height - 94
    },
    methods: {
      handleDelete(row) {
        if (row.renwudh) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await deleteWXRWD({ id: row.id })
            this.$baseMessage(msg, 'success')
            this.fetchData()
          })
        } else {
          this.$refs.plxTable.remove(row)
        }
      },
      async getRwList() {
        const res = await queryWXRWDListAll({ weixiud: this.ruleForm.weixiudh })
        this.$refs.plxTable.reloadData(res.data)
        this.Rwlist = res.data
      },
      goBack() {
        this.$parent.addshow = false
      },

      DialogOpenWuzi(row) {
        this.alltable = this.$refs.plxTable.getTableData().fullData
        // this.$refs['wuzi-dialog'].getData()
        this.$refs['wuzi-dialog'].showEdit()
      },
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            var msg = null
            if (this.gobacktitle == '编辑') {
              msg = await updateWxd(this.ruleForm)
            } else {
              msg = await addWxd(this.ruleForm)
            }
            if (msg.code == 200 && this.gobacktitle == '编辑') {
              let updateData = this.$refs.plxTable.getTableData().fullData
              if (updateData.length > 0) {
                updateData.forEach((item) => {
                  if (!item.renwudh) {
                    let ruleForm = {
                      weixiudid: this.ruleForm.id,
                      weixiud: this.ruleForm.weixiudh,
                      guajiaid: item.id,
                      tuopanid: item.tuopanid,
                      huoweiid: item.huoweiid,
                      huoweih: item.huoweibh,
                      tuopanh: item.tuopanbh,
                      guajia:
                        item.mingcheng +
                        '-' +
                        item.xingbie +
                        '-' +
                        item.chuchanghm,
                      zhuangtai: 1,
                    }
                    this.insertrwd(item, ruleForm)
                  }
                })
              }
            }
            this.$baseMessage('操作成功', 'success')
            this.goBack()
            this.$parent.resetlist()
          } else {
            return false
          }
        })
      },

      resetForm(formName) {
        this.ruleForm = Object.assign({ baofeidmxEntities: [] }, [])
        this.$nextTick(() => {
          this.$refs.plxTable.reloadData([])
        })
        // this.$refs[formName].resetFields()
      },
      selectChange(e) {},
      // 添加插入行
      // async insertEvent(row) {
      //   let record = this.insertData
      //   // 加入行, 表示加入行的row对象，row为空则插入第一行，为-1插入最后一行
      //   let { row: newRow } = await this.$refs.plxTable.insertRow(record)
      //   // 激活单元格编辑
      //   await this.$refs.plxTable.setActiveRow(newRow)
      // },
      delwzDetail() {
        this.$refs.plxTable.remove(this.$refs.plxTable.getCheckboxRecords())
      },
      uploadSuccess() {
        this.importShow = false
      },
      oninput(num) {
        return num.replace(/\D/g, '')
      },
      // fetchData() {
      //   this.getRwList()
      // },
      async insertEvent(row) {
        this.$nextTick(() => {
          this.$refs.plxTable.reloadData(this.Rwlist.concat(this.insertData))
        })
      },
      fetchData(data) {
        data.forEach((item) => {
          item.weixiudid = this.ruleForm.id
          item.weixiud = this.ruleForm.weixiudh
          item.guajiaid = item.id
          item.guajia =
            item.mingcheng + '-' + item.xingbie + '-' + item.chuchanghm
          item.tuopanid = item.tuopanid
          item.tuopanh = item.tuopanbh
          item.huoweiid = item.huoweiid
          item.huoweih = item.huoweibh
          item.zhuangtai = 1
        })
        this.insertData = data
        this.insertEvent()
      },
      async insertrwd(row, ruleForm) {
        let that = this
        // let ruleForm = {
        //   weixiudid: this.dataBH.id,
        //   weixiud: this.dataBH.weixiudh,
        //   guajiaid: row.id,
        //   tuopanid: row.tuopanid,
        //   huoweiid: row.huoweiid,
        //   huoweih: row.huoweibh,
        //   tuopanh: row.tuopanbh,
        //   guajia: row.weiyibm,
        //   zhuangtai: 1,
        // }
        let p1 = new Promise((resolve, reject) => {
          updateguajia(
            Object.assign(row, {
              caozuozt: 3,
            })
          )
            .then((res) => {
              resolve(res)
            })
            .catch((err) => {
              reject(err)
            })
        })
        let p2 = new Promise((resolve, reject) => {
          addWXRWD(ruleForm)
            .then((res) => {
              resolve(res)
            })
            .catch((err) => {
              reject(err)
            })
        })
        Promise.all([p1, p2])
          .then((res) => {
            // that.$message({
            //   message: '创建任务成功',
            //   type: 'success',
            // })
            // that.$emit('fetch-data', that.selectRows)
            // that.close()
          })
          .catch((err) => {
            console.log(err)
            that.$message({
              message: '创建失败',
              type: 'error',
            })
          })
      },
    },
  }
</script>
<style lang="scss" scoped>
  .add-container {
    position: fixed;
    left: 0;
    top: 0.75rem;
    width: 100%;
    height: 100%;
    z-index: 1000;
    background-color: #f6f8f9;
    padding: 0 0.2rem 1rem 0.2rem;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .add-top {
      padding: 0.1rem 0;

      ::v-deep .el-page-header__title {
        font-size: 0.16rem !important;
      }
    }

    .add-main {
      flex: 1;
      font-weight: bold;
      display: flex;
      flex-direction: column;
      overflow: auto;

      .add-main-top {
        padding: 0.2rem;
        background: #fff;
        border-radius: 0.05rem;

        .add-main-tital {
          font-size: 0.18rem;
          border-left: 0.1rem solid rgb(121, 189, 255);
          padding-left: 0.1rem;

          p {
            margin: 0;
          }
        }

        .search-gropu-item {
          margin-top: 0.2rem;
          width: 90%;
          display: flex;
          // label {
          //   white-space: nowrap;
          //   line-height: 32px;
          //   margin-right: 10px;
          // }
        }

        .el-select {
          width: 100%;
        }
      }

      .add-main-list {
        flex: 1;
        margin-top: 20px;
        background: #fff;
        padding: 20px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;

        .list-button-group {
          display: flex;
          flex-direction: row;
          padding-bottom: 20px;

          .button-item {
            padding: 0px 10px;
          }

          .button-item:first-child,
          &:last-child {
            padding: 0px 10px 0 0;
          }
        }

        .table-list {
          flex: 1;
        }
      }

      .el-button {
        font-size: 0.14rem !important;
      }

      ::v-deep {
        .elx-table--header-wrapper {
          background-color: rgb(233, 243, 255);
        }

        .elx-table {
          font-size: 0.14rem !important;
        }

        .elx-body--column {
          height: 0.48rem !important;
          line-height: 0.24rem;
        }

        .elx-header--column {
          background-image: none !important;
          height: 0.48rem !important;
        }

        .el-date-editor.el-input,
        .el-date-editor.el-input--inner {
          width: 100% !important;
        }

        .el-form-item--small.el-form-item {
          margin-bottom: 0px;
          margin-top: 18px;
        }
      }

      .submit-button {
        margin-top: 20px;
        display: flex;
        justify-content: center;
      }
    }
  }
</style>
